/*
 * TcpConnection.h
 *
 *  Created on: May 9, 2011
 *      Author: michael
 */

#ifndef TCPCONNECTION_H_
#define TCPCONNECTION_H_

#include "RawData.h"
#include <boost/shared_ptr.hpp>
#include <boost/asio.hpp>
#include <boost/thread/mutex.hpp>
#include <string>
#include <queue>
#include <vector>

namespace DerbyServ
{

class RawData;

class TcpConnection : public boost::enable_shared_from_this<TcpConnection>
{
public:
	static boost::shared_ptr<TcpConnection> Create(
			boost::asio::io_service & ioService_, int connectionId_);
	virtual ~TcpConnection();

	bool Send(const RawData & raw);
	bool Receive(RawData & raw);
	//TODO threading !!

	boost::asio::ip::tcp::socket & GetSocket();
	int GetId() const;

private:
	void WriteAsync();
	void ReadAsync();

	TcpConnection(boost::asio::io_service & ioService_, int connectionId_);
	void HandleWrite(const boost::system::error_code & error,
			std::size_t bytes_transferred);
	void HandleRead(
			const boost::system::error_code & error);
private:
	boost::asio::ip::tcp::socket _socket;
	int _id;

	std::queue< RawData > _writingRaws;
	boost::mutex _writingMutex;

	std::queue< RawData > _readingRaws;
	boost::mutex _readingMutex;
	bool _writingStarted;
	bool _readingStarted;

	RawData _writingRaw;
	RawData _readingRaw;

	enum ProtocolModes { MODE_META, MODE_DATA } _writingMode, _readingMode;
	//RawType _writingMeta, _readingMeta
};
typedef boost::shared_ptr<TcpConnection> TcpConnectionPtr;

} //namespace

#endif /* TCPCONNECTION_H_ */
